C++ Deque operator[]()

Last Updated : 14 May 2026

Deque operator[]() Function

In C++, the deque::operator[]()is used to access elements at a specified position in a deque container. It allows direct access to deque elements using an index value. This operator is commonly used for fast element access and modification in a deque. Unlike the at() function, it does not perform boundary checking.

Difference between operator[]() & at()

When position pos is greater than the size of the container, the operator[]() function returns a value 0. On the other hand, the at() function throws an exception i.e out of range.

Syntax

It has the following syntax:

Parameter

pos: It defines the position of an element which is to be accessed.

Return value

It returns a reference to an element at position pos in the deque container.

Examples of Deque operator[]() Function

Here, we are going to discuss several examples to demonstrate the deque operator[]() function.

Example 1: Access Elements from a Deque Using operator

This example demonstrates how to access deque elements using the operator[]() function.

Output:

mango is my favorite fruit 

Explanation:

In this example, operator[]() function access each element of deque a.

Example 2: Access an Out-of-Range Position Using operator

This example demonstrates what happens when an invalid position is accessed using the operator[]() function.

Output:

0

Explanation:

In this example, operator[]() function tries to access the position which is greater than the size of the container. Therefore, it returns 0.

Example 3: Modify Elements in a Deque Using operator

This example demonstrates how to modify deque elements using the operator[]() function.

Output:

10 100 30 200

Next TopicC++ Deque